export function throttle(fn, interval = 1000, options = {
  leading: true,
  trailing: false
}) {
  const {
    leading,
    trailing
  } = options;

  let startTime = 0;
  let timer = null;
  const _throttle = function (...args) {
    return new Promise((resolve, reject) => {
      let endTime = new Date().getTime();
      // 只有在第一次执行 和 leading = false;才能第一次延迟执行
      if (!startTime && !leading) startTime = endTime;

      const remainTime = interval - (endTime - startTime);

      if (remainTime <= 0) {
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }

        // 如果需要节流的函数 返回值是一个promsie对象; 则需要 resolve出去
        const result = fn.apply(this, args)

        resolve(result)
        
        startTime = endTime;
        return;
      }

      if (trailing && !timer) {
        timer = setTimeout(() => {
          timer = null;
          startTime = !leading ? 0 : new Date().getTime();
          fn.apply(this, args);
        }, remainTime);
      }
    })
  };

  _throttle.cancel = function () {
    if (timer) {
      clearTimeout(timer);
      timer = null;
      startTime = 0;
    }
  };

  return _throttle;
}